package com.bai.serviceOA.service.impl;

import com.bai.model.system.SysRole;
import com.bai.model.system.SysUserRole;
import com.bai.model.vo.AssginRoleVo;
import com.bai.serviceOA.mapper.SysRoleMapper;
import com.bai.serviceOA.service.SysRoleService;
import com.bai.serviceOA.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bai
 * @date 2023年03月07日 18:15
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 查询所有角色和当前用户所属角色
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Map<String, Object> findRoleDataByUserId(Long userId) {
        //1、查询所有的角色，返回list集合
        List<SysRole> allRoleList = baseMapper.selectList(null);

        //2、根据用户id查询角色用户关系表，查询用户id对应所有角色id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> existUserRoleList = sysUserRoleService.list(wrapper);

        //从查询出来的用户id对应角色list集合，获取所有角色id
        List<Long> existRoleList = existUserRoleList.stream().map(c -> c.getRoleId()).collect(Collectors.toList());

        //3、根据查询所有角色id，找到对应角色信息
        //根据角色id到所有的角色的list集合进行比较
        List<SysRole> assignedRoleList = new ArrayList<>();
        for (SysRole sysRole : allRoleList) {
            //比较
            if (existRoleList.contains(sysRole.getId())) {
                assignedRoleList.add(sysRole);
            }
        }

        //4、把得到的数据封装返回
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("assginRoleList", assignedRoleList);
        roleMap.put("assRolesList", allRoleList);
        return roleMap;
    }

    /**
     * 为用户分配角色
     *
     * @param assignRoleVo 一个用户对应多个角色
     */
    @Override
    public void doAssign(AssginRoleVo assignRoleVo) {
        //把用户之前分配的角色删除
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, assignRoleVo.getUserId());
        sysUserRoleService.remove(wrapper);
        //重新分配
        List<Long> roleIdList = assignRoleVo.getRoleIdList();
        for (Long roleId : roleIdList) {
            if (StringUtils.isEmpty(roleId)) {
                continue;
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assignRoleVo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRoleService.save(sysUserRole);
        }
    }
}
